# encoding:utf-8
class LinkedListStack:
    """
    基于链表实现的栈
    """
    def __init__(self):
        self.__peek: ListNode = None    # 将头节点作为栈顶
        self.__size: int = 0    # 栈的长度

    def size(self) -> int:
        """获取栈的长度"""
        return self.__size

    def is_empty(self) -> bool:
        """判断栈是否为空"""
        return self.__size == 0

    def push(self, val: int) -> None:
        """入栈"""
        node = ListNode(val)
        node.next = self.__peek
        self.__peek = node
        self.__size += 1

    def pop(self) -> int:
        """出栈"""
        num = self.peek()
        # 删除栈顶节点
        self.__peek = self.__peek.next
        self.__size -= 1
        return num

    def peek(self) -> int | None:
        """访问栈顶元素"""
        # 判空处理
        if self.__size == 0:
            return None
        return self.__peek.val

    def to_list(self) -> list[int]:
        """返回列表用于打印"""
        node = self.__peek
        res = []
        while node:
            res.append(node.val)
            node = node.next

        return res